package io.gitee.zhangbinhub.admin.resource.server.tools

import cn.dev33.satoken.oauth2.exception.SaOAuth2Exception
import com.fasterxml.jackson.databind.ObjectMapper
import io.gitee.zhangbinhub.acp.cloud.resource.server.constant.AcpCloudResourceServerConstant
import io.gitee.zhangbinhub.acp.cloud.resource.server.tools.TokenTools
import io.gitee.zhangbinhub.admin.resource.server.vo.TokenUserInfoVo
import org.bouncycastle.util.encoders.Base64

class TokenUserTools(private val objectMapper: ObjectMapper) {
    @Throws(SaOAuth2Exception::class)
    fun encryptUserInfo(userInfoVo: TokenUserInfoVo): String = try {
        Base64.toBase64String(objectMapper.writeValueAsBytes(userInfoVo))
    } catch (e: Exception) {
        throw SaOAuth2Exception(e.message)
    }

    @Throws(SaOAuth2Exception::class)
    fun decryptUserInfo(ciphertext: String): TokenUserInfoVo = try {
        objectMapper.readValue(Base64.decode(ciphertext), TokenUserInfoVo::class.java)
    } catch (e: Exception) {
        throw SaOAuth2Exception(e.message)
    }

    @Throws(SaOAuth2Exception::class)
    fun getUserInfoFromToken(accessToken: String? = null): TokenUserInfoVo =
        TokenTools.getAccessTokenModel(accessToken)?.let { atm ->
            decryptUserInfo(atm.extraData[AcpCloudResourceServerConstant.TOKEN_CLAIMS_USER_INFO].toString())
        } ?: TokenUserInfoVo()
}